from ProjectTool.common_tool.data_tool.file_uploaded import FileUploaded
from ProjectTool.common_tool.data_tool.get_query_dict import GetQueryDict
from ProjectTool.common_tool.data_tool.save_sql_detail import SaveSqlDetail
import json


class SaveData:
    def __init__(self, serializer, queryset, test_data):
        self.serializer = serializer
        self.test_data = test_data
        self.queryset = queryset
        self.headers = {
            'url': self.test_data.get('url'),
            'method': self.test_data.get('method'),
            'headers': self.test_data.get('headers'),
        }
        self.body = self.test_data.get('body_data')
        self.assert_data = self.test_data.get('assert_data')
        self.response_data = self.test_data.get('response_data')
        self.result_data = self.test_data.get('result_data')
        self.results = self.test_data.get('results')

    def get_query_dict(self):
        data = [
            (self.body, 'body'),
            (self.response_data, 'response'),
            (self.assert_data, 'assert_data'),
            (self.result_data, 'result_data'),
        ]
        query_dict = GetQueryDict().get_query()
        for dt in data:
            obj = FileUploaded(dt[0], ''.join([dt[1], '.txt'])).get_uploaded_file()
            query_dict.__setitem__(dt[1], obj)
        query_dict.__setitem__('results', self.results)
        query_dict.__setitem__('header', json.dumps(self.headers,ensure_ascii=False))
        return query_dict

    def save_data(self):
        query_dict = self.get_query_dict()
        obj = SaveSqlDetail(self.serializer, self.queryset, query_dict)
        obj.save()
        return obj.res
